package com.sinotrans.gateway.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import com.sinotrans.gateway.config.GatewayAuthIgnoreConfig;
import com.sinotrans.gateway.service.SecurityService;
import com.sinotrans.logger.util.Util;

@Service
public class SecurityServiceImpl implements SecurityService {
	final static Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

	private Object lock = new Object();

	private volatile AntPathMatcher ingorePattern = null;

	@Autowired
	private GatewayAuthIgnoreConfig authIgnore;

	@Override
	public boolean isAuthIgnoreUrl(String url) {
		if (authIgnore != null) {
			if (!Util.isEmpty(authIgnore.getUrls())) {
				boolean matching = false;
				for (String pattern : authIgnore.getUrls()) {
					matching = patternMatcher().match(pattern, url);
					if (matching) {
						return true;
					}
				}
			}
		}
		return false;
	}

	protected AntPathMatcher patternMatcher() {
		if (ingorePattern == null) {
			synchronized (lock) {
				if (ingorePattern == null) {
					ingorePattern = new AntPathMatcher();
				}
			}
		}
		return ingorePattern;
	}

}
